<template>
  <div class="add">
    <a-modal v-model:visible="visible" title="授权人员" @ok="form.onOk">
      <a-transfer v-model:target-keys="form.state.targetKeys" class="tree-transfer" :data-source="dataSource" :render="(item) => item.title" :show-select-all="false">
        <template #children="{ direction, selectedKeys, onItemSelect }">
          <a-tree
            v-if="direction === 'left'"
            block-node
            checkable
            check-strictly
            default-expand-all
            :checked-keys="[...selectedKeys, ...form.state.targetKeys]"
            :tree-data="treeData"
            @check="
              (_, props) => {
                onChecked(props, [...selectedKeys, ...form.state.targetKeys], onItemSelect)
              }
            "
            @select="
              (_, props) => {
                onChecked(props, [...selectedKeys, ...form.state.targetKeys], onItemSelect)
              }
            "
          />
        </template>
      </a-transfer>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import type { TransferProps } from 'ant-design-vue'
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, ref, watch } from 'vue'

  import { requestGetUserList } from '/@/api/business/company'
  import { requestSaveCompanyIdentityUserRef } from '/@/api/business/company/identity/user'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getCompanyInfo } from '/@/storage'
  const { companyId } = getCompanyInfo()
  const props = defineProps({
    visible: { type: Boolean, default: false },
    propsData: { type: Object, default: () => {} },
  })
  const emits = defineEmits(['update:visible', 'success'])
  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })
  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) initData()
    },
  )
  watch(
    () => props.propsData,
    () => {
      console.log('propsData:', props.propsData)
      form.state.targetKeys = props.propsData.userIds
    },
  )
  let transferDataSource: TransferProps['dataSource'] = []
  const dataSource = ref(transferDataSource)
  function flatten(list: TransferProps['dataSource'] = []) {
    list.forEach((item) => {
      transferDataSource.push(item)
      flatten(item.children)
    })
  }

  const data = ref<TransferProps['dataSource']>([])
  const getUserList = async () => {
    const { responseCode, responseData } = await requestGetUserList({ companyId: companyId })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      const setKey = (list) => {
        list.forEach((item) => {
          item.key = item.deptId || item.userId
          item.title = item.deptName || item.userName
          item.children = (item?.children?.length ? item.children : item.userList) || []
          delete item.disabled
          setKey((item?.children?.length ? item.children : item.userList) || [])
          if (item.userId) {
            item.isUser = true
          }
        })
      }
      setKey(responseData)
      data.value = responseData
      console.log(data.value)
      flatten(JSON.parse(JSON.stringify(data.value)))
    }
  }
  getUserList()
  function isChecked(selectedKeys: (string | number)[], eventKey: string | number) {
    return selectedKeys.indexOf(eventKey) !== -1
  }

  function handleTreeData(treeNodes, targetKeys: string[] = []) {
    return treeNodes.map(({ children, ...props }) => ({
      ...props,
      disabled: targetKeys.includes(props.key as string) || !props.isUser,
      children: handleTreeData(children ?? [], targetKeys),
    }))
  }

  const treeData = computed(() => {
    return handleTreeData(data.value, form.state.targetKeys)
  })

  const onChecked = (e, checkedKeys, onItemSelect: (n: any, c: boolean) => void) => {
    const { eventKey } = e.node
    onItemSelect(eventKey, !isChecked(checkedKeys, eventKey))
  }
  const initData = () => {
    resetFields()
  }

  /** 表单配置 */
  const form = reactive({
    state: {
      targetKeys: [],
    },
    rule: {
      name: [{ required: true, message: '请输入组织名称' }],
    },
    onOk: () => {
      validate()
        .then(async () => {
          const { responseCode } = await requestSaveCompanyIdentityUserRef({
            companyIdentityRefId: props.propsData.companyIdentityRefId,
            userIds: form.state.targetKeys,
          })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            message.success('授权成功')
            emits('success')
            visible.value = false
          }
        })
        .catch(() => {})
    },
  })
  /** 表单hook */
  const { validate, resetFields } = Form.useForm(form.state, form.rule)
</script>

<style lang="less" scoped></style>
